package com.xuecheng.manage_course.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.domain.cms.response.CmsPostPageResult;
import com.xuecheng.framework.domain.cms.response.QueryResponseResult;
import com.xuecheng.framework.domain.course.*;
import com.xuecheng.framework.domain.course.ext.CourseInfo;
import com.xuecheng.framework.domain.course.ext.CourseView;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.domain.course.request.CourseListRequest;
import com.xuecheng.framework.domain.course.response.AddCourseResult;
import com.xuecheng.framework.domain.course.response.CourseCode;
import com.xuecheng.framework.domain.course.response.CoursePreviewResult;
import com.xuecheng.framework.domain.course.response.CoursePublishResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.client.CmsPageClient;
import com.xuecheng.manage_course.client.SearchClient;
import com.xuecheng.manage_course.dao.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author ShengJinFeng
 * @version V1.0
 * @ClassName CourseService
 * @Description (这里用一句话描述这个类的作用)
 * @date 2020/2/1 13:27
 * @since V1.0
 */
@Service
public class CourseService {

    @Value("${course-publish.siteId:}")
    private String siteId;
    @Value("${course-publish.templateId:}")
    private String templateId;
    @Value("${course-publish.previewUrl:}")
    private String previewUrl;
    @Value("${course-publish.pageWebPath:}")
    private String pageWebPath;
    @Value("${course-publish.pagePhysicalPath:}")
    private String pagePhysicalPath;
    @Value("${course-publish.dataUrlPre:}")
    private String dataUrlPre;

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private TeachplanRepository teachplanRepository;

    @Autowired
    private CourseBaseRepository courseBaseRepository;

    @Autowired
    private CourseMarketRepository courseMarketRepository;

    @Autowired
    private CoursePicRepository coursePicRepository;

    @Autowired
    private CmsPageClient cmsPageClient;

    @Autowired
    private SearchClient searchClient;

    @Autowired
    private CoursePubRepository coursePubRepository;

    @Autowired
    private TeachplanMediaRepository teachplanMediaRepository;

    /**
     * @Description 根据课程id查询教学计划列表
     * @author ShengJinFeng
     * @date 2020/2/1
     */
    public TeachplanNode findTeachplanList(String courseId) {
        return teachplanMapper.selectTeachplanList(courseId);
    }

    /**
     * @Description 添加课程计划
     * @author ShengJinFeng
     * @date 2020/2/1
     */
    @Transactional
    public void addTeachplan(Teachplan teachplan) {
        //校验课程id和课程计划名称
        if(teachplan == null || StringUtils.isEmpty(teachplan.getCourseid()) || StringUtils.isEmpty(teachplan.getPname())){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        Teachplan teach = new Teachplan();
        BeanUtils.copyProperties(teachplan,teach);
        //取出课程id
        String courseid = teach.getCourseid();
        //取出父结点id
        String parentid = teach.getParentid();
        if(StringUtils.isEmpty(parentid)){
            //如果父结点为空则获取根结点
            parentid= getTeachplanRoot(courseid);
        }
        //取出父结点信息
        Optional<Teachplan> teachplanOptional = teachplanRepository.findById(parentid);
        if(!teachplanOptional.isPresent()){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        //父结点
        Teachplan teachplanParent = teachplanOptional.get();
        //父结点级别
        String parentGrade = teachplanParent.getGrade();
        //设置父结点
        teach.setParentid(parentid);
        //未发布 //子结点的级别，根据父结点来判断
        if(parentGrade.equals("1")){
            teach.setGrade("2");
        }else if(parentGrade.equals("2")){
            teach.setGrade("3");
        }
        //设置课程id
        teachplanRepository.save(teach);
    }


    /**
     * @Description 获取课程根节点，如果没有则添加根节点
     * @author ShengJinFeng
     * @date 2020/2/1
     */
    private String getTeachplanRoot(String courseId){
        //检验课程
        Optional<CourseBase> optional = courseBaseRepository.findById(courseId);
        if (!optional.isPresent()){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        CourseBase courseBase = optional.get();
        List<Teachplan> teachplans = teachplanRepository.findByCourseidAndParentid(courseId, "0");
        if (CollectionUtils.isEmpty(teachplans)){//新增根结点
            Teachplan teachplanRoot = new Teachplan();
            teachplanRoot.setPname(courseBase.getName());
            teachplanRoot.setParentid("0");
            teachplanRoot.setGrade("1");
            teachplanRoot.setCourseid(courseId);
            teachplanRepository.save(teachplanRoot);
            return teachplanRoot.getId();
        }
        Teachplan teachplan = teachplans.get(0);
        return teachplan.getId();
    }

    /**
     * @Description 查询我的课程列表
     * @author ShengJinFeng
     * @date 2020/2/3
     */
    public QueryResponseResult findCourseList(int page, int size, CourseListRequest courseListRequest) {

        if(courseListRequest == null){
            courseListRequest = new CourseListRequest();
        }
        if(page<=0){
            page = 0;
        }
        if(size<=0){
            size = 20;
        }
        //设置分页参数
        PageHelper.startPage(page, size);
        //分页查询
        Page<CourseInfo> courseListPage = courseMapper.findCourseListPage(courseListRequest);
        //查询列表
        List<CourseInfo> list = courseListPage.getResult();
        //总记录数
        long total = courseListPage.getTotal();
        //查询结果集
        QueryResult<CourseInfo> courseIncfoQueryResult = new QueryResult<CourseInfo>();
        courseIncfoQueryResult.setList(list);
        courseIncfoQueryResult.setTotal(total);
        return new QueryResponseResult(CommonCode.SUCCESS, courseIncfoQueryResult);
    }

    /**
     * @Description 添加课程基本信息
     * @author ShengJinFeng
     * @date 2020/2/3
     */
    @Transactional
    public AddCourseResult addCourse(CourseBase courseBase) {
        courseBase.setStatus("202001");
        courseBaseRepository.save(courseBase);
        return new AddCourseResult(CommonCode.SUCCESS,courseBase.getId());
    }

    /**
     * @Description 根据课程id获取课程基础信息 
     * @author ShengJinFeng
     * @date 2020/2/7
     */
    public CourseBase getCourseBaseById(String courseId) {
        Optional<CourseBase> optional = courseBaseRepository.findById(courseId);
        if (!optional.isPresent()){
            return null;
        }
        return optional.get();
    }

    /**
     * @Description 更新课程基础信息
     * @author ShengJinFeng
     * @date 2020/2/7
     */
    @Transactional
    public ResponseResult updateCourseBase(CourseBase courseBase) {
        courseBaseRepository.save(courseBase);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * @Description 获取课程营销信息
     * @author ShengJinFeng
     * @date 2020/2/7
     */
    public CourseMarket getCourseMarketById(String courseId) {
        Optional<CourseMarket> optional = courseMarketRepository.findById(courseId);
        if (!optional.isPresent()){
            return null;
        }
        return optional.get();
    }

    /**
     * @Description 更新课程营销信息
     * @author ShengJinFeng
     * @date 2020/2/7
     */
    @Transactional
    public ResponseResult updateCourseMarket(CourseMarket courseMarket) {
        courseMarketRepository.save(courseMarket);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * @Description 添加课程图片
     * @author ShengJinFeng
     * @date 2020/2/10
     */
    @Transactional
    public ResponseResult addCoursePic(String courseId, String pic) {
        CoursePic coursePic = new CoursePic();
        coursePic.setCourseid(courseId);
        coursePic.setPic(pic);
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * @Description 获取课程图片
     * @author ShengJinFeng
     * @date 2020/2/10
     */
    public CoursePic findCoursePicById(String courseId) {
        Optional<CoursePic> optional = coursePicRepository.findById(courseId);
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    /**
     * @Description 删除课程图片
     * @author ShengJinFeng
     * @date 2020/2/10
     */
    @Transactional
    public ResponseResult deleteCoursePic(String courseId) {
        long result = coursePicRepository.deleteByCourseid(courseId);
        if (result >0){
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }

    /**
     * @Description 课程视图查询
     * @author ShengJinFeng
     * @date 2020/2/18
     */
    public CourseView getCourseViewById(String id) {
        CourseView courseView = new CourseView();
        CourseBase courseBase = getCourseBaseById(id);
        courseView.setCourseBase(courseBase);
        CourseMarket courseMarket = getCourseMarketById(id);
        courseView.setCourseMarket(courseMarket);
        CoursePic coursePic = findCoursePicById(id);
        courseView.setCoursePic(coursePic);
        TeachplanNode teachplanNode = findTeachplanList(id);
        courseView.setTeachplanNode(teachplanNode);
        return courseView;
    }

    /**
     * @Description 预览课程
     * @author ShengJinFeng
     * @date 2020/2/18
     */
    public CoursePreviewResult preview(String id) {
        CourseBase courseBase = getCourseBaseById(id);
        //远程调用接口保存页面，得到页面id
        CmsPage cmsPage = new CmsPage();
        cmsPage.setSiteId(siteId);
        cmsPage.setPageName(id+".html");
        cmsPage.setPageAliase(courseBase.getName());
        cmsPage.setPageWebPath(pageWebPath);
        cmsPage.setPagePhysicalPath(pagePhysicalPath);
        cmsPage.setTemplateId(templateId);
        cmsPage.setDataUrl(dataUrlPre+id);
        cmsPage.setPageCreateTime(new Date());
        CmsPageResult cmsPageResult = cmsPageClient.saveCmsPage(cmsPage);
        if (!cmsPageResult.isSuccess()){
            return new CoursePreviewResult(CommonCode.FAIL,null);
        }
        //组装预览页面的url
        String pageId = cmsPageResult.getCmsPage().getPageId();
        String url = previewUrl+pageId;
        //返回结果
        return new CoursePreviewResult(CommonCode.SUCCESS,url);
    }

    /**
     * @Description 发布课程
     * @author ShengJinFeng
     * @date 2020/2/19
     */
    @Transactional
    public CoursePublishResult publish(String id) {
        //获取课程信息
        CourseBase courseBase = getCourseBaseById(id);
        //远程调用接口保存页面，得到页面id
        //拼装页面信息
        CmsPage cmsPage = new CmsPage();
        cmsPage.setSiteId(siteId);
        cmsPage.setPageName(id+".html");
        cmsPage.setPageAliase(courseBase.getName());
        cmsPage.setPageWebPath(pageWebPath);
        cmsPage.setPagePhysicalPath(pagePhysicalPath);
        cmsPage.setTemplateId(templateId);
        cmsPage.setDataUrl(dataUrlPre+id);
        cmsPage.setPageCreateTime(new Date());
        //远程调用cms页面发布接口，发布页面
        CmsPostPageResult postPageResult = cmsPageClient.postPageQuick(cmsPage);
        if (!postPageResult.isSuccess()){
            ExceptionCast.cast(CommonCode.FAIL);
        }
        //修改课程得状态为已发布
        courseBase.setStatus("202002");
        updateCourseBase(courseBase);
        //保存课程索引信息
        CoursePub coursePub = saveCoursePub(id);
        if (coursePub == null){
            ExceptionCast.cast(CourseCode.COURSE_PUBLISH_CREATE_INDEX_ERROR);
        }
        searchClient.addEsCourse(coursePub);
        //保持课程计划媒资信息到ES
        saveTeachplanMediaToEs(id);
        //缓存课程的信息

        //获取页面url，返回结果
        String pageUrl = postPageResult.getPageUrl();
        return new CoursePublishResult(CommonCode.SUCCESS,pageUrl);
    }

    /**
     * @Description 查询课程信息列表
     * @author ShengJinFeng
     * @date 2020/2/20
     */
    public List<CoursePub> findCoursePubList() {
        List<CoursePub> all = coursePubRepository.findAll();
        return all;
    }

    /**
     * @Description 保存课程计划的媒资信息
     * @author ShengJinFeng
     * @date 2020/3/4
     */
    public ResponseResult saveTeachplanMedia(TeachplanMedia teachplanMedia) {
        if (teachplanMedia == null || StringUtils.isEmpty(teachplanMedia.getTeachplanId())){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        //检查教学计划是否存在
        Optional<Teachplan> optionalTeachplan = teachplanRepository.findById(teachplanMedia.getTeachplanId());
        if (!optionalTeachplan.isPresent()){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        //只允许为叶子的教学计划有媒资文件
        Teachplan teachplan = optionalTeachplan.get();
        if (StringUtils.isEmpty(teachplan.getGrade()) || !teachplan.getGrade().equals("3")){
            ExceptionCast.cast(CourseCode.COURSE_MEDIA_TEACHPLAN_GRADEERROR);
        }
        teachplanMediaRepository.save(teachplanMedia);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * @Description 获取所有课程计划的媒资信息
     * @author ShengJinFeng
     * @date 2020/3/6
     */
    public List<TeachplanMedia> findTeachplanMedias() {
        return teachplanMediaRepository.findAll();
    }

    /**
     * @Description 保存课程索引信息
     * @author ShengJinFeng
     * @date 2020/2/19
     */
    private CoursePub saveCoursePub(String id) {
        //构建coursePub
        CoursePub coursePub = createCoursePub(id);
        coursePub.setTimestamp(new Date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
        String dateString = simpleDateFormat.format(new Date());
        coursePub.setPubTime(dateString);
        return coursePubRepository.save(coursePub);
    }

    /**
     * @Description 构建coursePub
     * @author ShengJinFeng
     * @date 2020/2/19
     */
    private CoursePub createCoursePub(String id) {
        CoursePub coursePub = new CoursePub();
        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);
        if (courseBaseOptional.isPresent()){
            BeanUtils.copyProperties(courseBaseOptional.get(),coursePub);
        }
        Optional<CoursePic> coursePicOptional = coursePicRepository.findById(id);
        if (coursePicOptional.isPresent()){
            BeanUtils.copyProperties(coursePicOptional.get(),coursePub);
        }
        Optional<CourseMarket> courseMarketOptional = courseMarketRepository.findById(id);
        if (courseMarketOptional.isPresent()){
            BeanUtils.copyProperties(courseMarketOptional.get(),coursePub);
        }
        TeachplanNode teachplanNode = teachplanMapper.selectTeachplanList(id);
        String teachplan = JSON.toJSONString(teachplanNode);
        coursePub.setTeachplan(teachplan);
        coursePub.setId(id);
        return coursePub;
    }

    /**
     * @Description 保持课程计划媒资信息到ES
     * @author ShengJinFeng
     * @date 2020/3/6
     */
    private void saveTeachplanMediaToEs(String id) {
        //根据课程id查询课程计划得媒资信息
        List<TeachplanMedia> list = teachplanMediaRepository.findByCourseId(id);
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        searchClient.addEsTeachplanMedia(list);
    }
}
